<?php

/**

 * Description of common functions

 *

 * @author csyr

 */
define("IS_CLI", TRUE);

define("IS_WIN", FALSE);

define("DATA_PATH", "./");

/**

 * UTF-8 字符截取

 *

 * @param   string      $str

 * @param   int         $length

 * @param   bool        $append

 *

 * @return  string

 */
function sub_str($str, $length = 0, $append = true, $charset="utf-8") {

    $str = trim($str);

    $strlength = strlen($str);



    if ($length == 0 || $length >= $strlength) {

        return $str;
    } elseif ($length < 0) {

        $length = $strlength + $length;

        if ($length < 0) {

            $length = $strlength;
        }
    }



    if (function_exists('mb_substr')) {

        $newstr = mb_substr($str, 0, $length, $charset);
    } elseif (function_exists('iconv_substr')) {

        $newstr = iconv_substr($str, 0, $length, $charset);
    } else {

        //$newstr = trim_right(substr($str, 0, $length));

        $newstr = trim(substr($str, 0, $length));
    }



    if ($append && $str != $newstr) {

        $newstr .= '...';
    }



    return $newstr;
}

/**

 * 字符串长度

 *

 * @param   string      $str 

 *

 * @return  int

 */
function str_len($str) {

    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));



    if ($length) {

        return strlen($str) - $length + intval($length / 3) * 2;
    } else {

        return strlen($str);
    }
}

/**

 * 适应当前系统的换行符

 * @access  public

 * @return  string

 */
function get_crlf() {

    if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) {

        $the_crlf = '\r\n';
    } elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) {

        $the_crlf = '\r'; // for old MAC OS
    } else {

        $the_crlf = '\n';
    }



    return $the_crlf;
}

/**

  +----------------------------------------------------------

 * 字符串命名风格转换

 * type

 * =0 将Java风格转换为C的风格

 * =1 将C风格转换为Java的风格

  +----------------------------------------------------------

 * @access protected

  +----------------------------------------------------------

 * @param string $name 字符串

 * @param integer $type 转换类型

  +----------------------------------------------------------

 * @return string

  +----------------------------------------------------------

 */
function parse_name($name, $type=0) {

    if ($type) {

        return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
    } else {

        $name = preg_replace("/[A-Z]/", "_\\0", $name);

        return strtolower(trim($name, "_"));
    }
}

// 错误输出

function halt($error) {

    if (IS_CLI)
        exit($error);

    $e = array();

    if (C('APP_DEBUG')) {

        //调试模式下输出错误信息

        if (!is_array($error)) {

            $trace = debug_backtrace();

            $e['message'] = $error;

            $e['file'] = $trace[0]['file'];

            $e['class'] = $trace[0]['class'];

            $e['function'] = $trace[0]['function'];

            $e['line'] = $trace[0]['line'];

            $traceInfo = '';

            $time = date("y-m-d H:i:m");

            foreach ($trace as $t) {

                $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';

                $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';

                $traceInfo .= implode(', ', $t['args']);

                $traceInfo .=")<br/>";
            }

            $e['trace'] = $traceInfo;
        } else {

            $e = $error;
        }

        // 包含异常页面模板

        include C('TMPL_EXCEPTION_FILE');
    } else {

        //否则定向到错误页面

        $error_page = C('ERROR_PAGE');

        if (!empty($error_page)) {

            redirect($error_page);
        } else {

            if (C('SHOW_ERROR_MSG'))
                $e['message'] = is_array($error) ? $error['message'] : $error;

            else
                $e['message'] = C('ERROR_MESSAGE');

            // 包含异常页面模板

            include C('TMPL_EXCEPTION_FILE');
        }
    }

    exit;
}

// URL重定向

function redirect($url, $time=0, $msg='') {

    //多行URL地址支持

    $url = str_replace(array("\n", "\r"), '', $url);
    if (!env_can_rewrite ()) {
        $url = Q . $url;
    }

    if (empty($msg))
        $msg = ''; //"系统将在{$time}秒之后自动跳转到{$url}！";

        if (!headers_sent()) {

        // redirect       

        if (0 === $time) {

            header("Location: " . $url);
        } else {

            header("refresh:{$time};url={$url}");

            $msg = "<p style='margin:10px;padding:10px;border:1px solid #CCFFFF;font:300 12px arial;background-color:#F1F9FC;color:green;'>$msg</p>";

            echo($msg);
        }

        exit();
    } else {

        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";

        if ($time != 0) {

            $msg = "<p style='margin:10px;padding:10px;border:1px solid #CCFFFF;font:300 12px arial;background-color:#F1F9FC;color:green;'>$msg</p>";

            $str .= $msg;
        }

        exit($str);
    }
}

// 自定义异常处理

function throw_exception($msg, $type='Exception', $code=0) {

    if (IS_CLI)
        exit($msg);

    if (class_exists($type, false))
        throw new Exception($msg, $code, true);

    //throw new $type($msg,$code,true);

    else
        halt($msg);        // 异常类型不存在则输出错误信息字串





}

// 区间调试开始

function debug_start($label='') {

    $GLOBALS[$label]['_beginTime'] = microtime(TRUE);

    if (MEMORY_LIMIT_ON)
        $GLOBALS[$label]['_beginMem'] = memory_get_usage();
}

// 区间调试结束，显示指定标记到当前位置的调试

function debug_end($label='') {

    $GLOBALS[$label]['_endTime'] = microtime(TRUE);

    echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's ';

    if (MEMORY_LIMIT_ON) {

        $GLOBALS[$label]['_endMem'] = memory_get_usage();

        echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k';
    }

    echo '</div>';
}

// 浏览器友好的变量输出

function dump($var, $echo=true, $label=null, $strict=true) {

    $label = ($label === null) ? '' : rtrim($label) . ' ';

    if (!$strict) {

        if (ini_get('html_errors')) {

            $output = print_r($var, true);

            $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
        } else {

            $output = $label . " : " . print_r($var, true);
        }
    } else {

        ob_start();

        var_dump($var);

        $output = ob_get_clean();

        if (!extension_loaded('xdebug')) {

            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);

            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }

    if ($echo) {

        echo($output);

        return null;
    }else
        return $output;
}

/**

 * 获得用户的真实IP地址

 *

 * @access  public

 * @return  string

 */
function real_ip() {

    static $realip = NULL;



    if ($realip !== NULL) {

        return $realip;
    }



    if (isset($_SERVER)) {

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {

            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);



            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */

            foreach ($arr AS $ip) {

                $ip = trim($ip);



                if ($ip != 'unknown') {

                    $realip = $ip;



                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {

            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {

            if (isset($_SERVER['REMOTE_ADDR'])) {

                $realip = $_SERVER['REMOTE_ADDR'];
            } else {

                $realip = '0.0.0.0';
            }
        }
    } else {

        if (getenv('HTTP_X_FORWARDED_FOR')) {

            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {

            $realip = getenv('HTTP_CLIENT_IP');
        } else {

            $realip = getenv('REMOTE_ADDR');
        }
    }



    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);

    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';



    return $realip;
}

// 取得对象实例 支持调用类的静态方法

function get_instance_of($name, $method='', $args=array()) {

    static $_instance = array();

    $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);

    if (!isset($_instance[$identify])) {

        if (class_exists($name)) {

            $o = new $name();

            if (method_exists($o, $method)) {

                if (!empty($args)) {

                    $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
                } else {

                    $_instance[$identify] = $o->$method();
                }
            }

            else
                $_instance[$identify] = $o;
        }

        else
            halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
    }

    return $_instance[$identify];
}

// 优化的require_once

function require_cache($filename) {

    static $_importFiles = array();

    $filename = realpath($filename);

    if (!isset($_importFiles[$filename])) {

        if (file_exists_case($filename)) {

            require $filename;

            $_importFiles[$filename] = true;
        } else {

            $_importFiles[$filename] = false;
        }
    }

    return $_importFiles[$filename];
}

// 区分大小写的文件存在判断

function file_exists_case($filename) {

    if (is_file($filename)) {

        if (IS_WIN && C('APP_FILE_CASE')) {

            if (basename(realpath($filename)) != basename($filename))
                return false;
        }

        return true;
    }

    return false;
}

// 快速定义和导入别名

function alias_import($alias, $classfile='') {

    static $_alias = array();

    if ('' !== $classfile) {

        // 定义别名导入

        $_alias[$alias] = $classfile;

        return;
    }

    if (is_string($alias)) {

        if (isset($_alias[$alias]))
            return require_cache($_alias[$alias]);
    }elseif (is_array($alias)) {

        foreach ($alias as $key => $val)
            $_alias[$key] = $val;

        return;
    }

    return false;
}

// 获取和设置语言定义(不区分大小写)

function L($name=null, $value=null) {

    static $_lang = array();

    // 空参数返回所有定义

    if (empty($name))
        return $_lang;

    // 判断语言获取(或设置)
    // 若不存在,直接返回全大写$name

    if (is_string($name)) {

        $name = strtoupper($name);

        if (is_null($value))
            return isset($_lang[$name]) ? $_lang[$name] : $name;

        $_lang[$name] = $value; // 语言定义

        return;
    }

    // 批量定义

    if (is_array($name))
        $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));

    return;
}

// 处理标签

function tag($name, $params=array()) {

    $tags = C('_tags_.' . $name);

    if ($tags) {

        foreach ($tags as $key => $call) {

            if (is_callable($call))
                $result = call_user_func_array($call, $params);
        }

        return $result;
    }

    return false;
}

// 快速文件数据读取和保存 针对简单类型数据 字符串、数组

function F($name, $value='', $path=DATA_PATH) {

    static $_cache = array();

    $filename = $path . $name . '.php';

    if ('' !== $value) {

        if (is_null($value)) {

            // 删除缓存

            return unlink($filename);
        } else {

            // 缓存数据

            $dir = dirname($filename);

            // 目录不存在则创建

            if (!is_dir($dir))
                mkdir($dir);

            return file_put_contents($filename, "<?php\n return " . var_export($value, true) . ";\n?>");
        }
    }

    if (isset($_cache[$name]))
        return $_cache[$name];

    // 获取缓存数据

    if (is_file($filename)) {

        $value = include $filename;

        $_cache[$name] = $value;
    } else {

        $value = false;
    }

    return $value;
}

// 根据PHP各种类型变量生成唯一标识号

function to_guid_string($mix) {

    if (is_object($mix) && function_exists('spl_object_hash')) {

        return spl_object_hash($mix);
    } elseif (is_resource($mix)) {

        $mix = get_resource_type($mix) . strval($mix);
    } else {

        $mix = serialize($mix);
    }

    return md5($mix);
}

//[RUNTIME]
// 编译文件

function compile($filename, $runtime=false) {

    $content = file_get_contents($filename);

    if (true === $runtime)

    // 替换预编译指令
        $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);

    $content = substr(trim($content), 5);

    if ('?>' == substr($content, -2))
        $content = substr($content, 0, -2);

    return $content;
}

// 去除代码中的空白和注释

function strip_whitespace($content) {

    $stripStr = '';

    //分析php源码

    $tokens = token_get_all($content);

    $last_space = false;

    for ($i = 0, $j = count($tokens); $i < $j; $i++) {

        if (is_string($tokens[$i])) {

            $last_space = false;

            $stripStr .= $tokens[$i];
        } else {

            switch ($tokens[$i][0]) {

                //过滤各种PHP注释

                case T_COMMENT:

                case T_DOC_COMMENT:

                    break;

                //过滤空格

                case T_WHITESPACE:

                    if (!$last_space) {

                        $stripStr .= ' ';

                        $last_space = true;
                    }

                    break;

                default:

                    $last_space = false;

                    $stripStr .= $tokens[$i][1];
            }
        }
    }

    return $stripStr;
}

// 根据数组生成常量定义

function array_define($array) {

    $content = '';

    foreach ($array as $key => $val) {

        $key = strtoupper($key);

        if (in_array($key, array('THINK_PATH', 'APP_NAME', 'APP_PATH', 'RUNTIME_PATH', 'RUNTIME_ALLINONE', 'THINK_MODE')))
            $content .= 'if(!defined(\'' . $key . '\')) ';

        if (is_int($val) || is_float($val)) {

            $content .= "define('" . $key . "'," . $val . ");";
        } elseif (is_bool($val)) {

            $val = ($val) ? 'true' : 'false';

            $content .= "define('" . $key . "'," . $val . ");";
        } elseif (is_string($val)) {

            $content .= "define('" . $key . "','" . addslashes($val) . "');";
        }
    }

    return $content;
}

//[/RUNTIME]
// 循环创建目录

function mk_dir($dir, $mode = 0755) {

    if (is_dir($dir) || @mkdir($dir, $mode))
        return true;

    if (!mk_dir(dirname($dir), $mode))
        return false;

    return @mkdir($dir, $mode);
}

// 自动转换字符集 支持数组转换

function auto_charset($fContents, $from, $to) {

    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;

    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;

    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {

        //如果编码相同或者非字符串标量则不转换

        return $fContents;
    }

    if (is_string($fContents)) {

        if (function_exists('mb_convert_encoding')) {

            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {

            return iconv($from, $to, $fContents);
        } else {

            return $fContents;
        }
    } elseif (is_array($fContents)) {

        foreach ($fContents as $key => $val) {

            $_key = auto_charset($key, $from, $to);

            $fContents[$_key] = auto_charset($val, $from, $to);

            if ($key != $_key)
                unset($fContents[$key]);
        }

        return $fContents;
    }

    else {

        return $fContents;
    }
}

// xml编码

function xml_encode($data, $encoding='utf-8', $root="root") {

    $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';

    if (is_object($data) || is_array($data)) {

        $dataNum = count($data);
    }

    $xml.=$dataNum == 1 ? '' : '<' . $root . '>';

    $xml.= data_to_xml($data);

    $xml.=$dataNum == 1 ? '' : '</' . $root . '>';

    return $xml;
}

function data_to_xml($data) {

    if (is_object($data)) {

        $data = get_object_vars($data);
    }

    $xml = '';

    foreach ($data as $key => $val) {

        is_numeric($key) && $key = "item id=\"$key\"";

        $xml.="<$key>";

        $xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;

        list($key, ) = explode(' ', $key);

        $xml.="<$key>";
    }

    return $xml;
}

/**

  +----------------------------------------------------------

 * Cookie 设置、获取、清除 (支持数组或对象直接设置)

  +----------------------------------------------------------

 * 1 获取cookie: cookie('name')

 * 2 清空当前设置前缀的所有cookie: cookie(null)

 * 3 删除指定前缀所有cookie: cookie(null,'think_') | 注：前缀将不区分大小写

 * 4 设置cookie: cookie('name','value') | 指定保存时间: cookie('name','value',3600)

 * 5 删除cookie: cookie('name',null)

  +----------------------------------------------------------

 * $option 可用设置prefix,expire,path,domain

 * 支持数组形式:cookie('name','value',array('expire'=>1,'prefix'=>'think_'))

 * 支持query形式字符串:cookie('name','value','prefix=tp_&expire=10000')

 */
function cookie($name, $value='', $option=null) {

    // 默认设置

    $config = array(
        'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀

        'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间

        'path' => C('COOKIE_PATH'), // cookie 保存路径

        'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名
    );

    // 参数设置(会覆盖黙认设置)

    if (!empty($option)) {

        if (is_numeric($option))
            $option = array('expire' => $option);

        elseif (is_string($option))
            parse_str($option, $option);

        array_merge($config, array_change_key_case($option));
    }

    // 清除指定前缀的所有cookie

    if (is_null($name)) {

        if (empty($_COOKIE))
            return;

        // 要删除的cookie前缀，不指定则删除config设置的指定前缀

        $prefix = empty($value) ? $config['prefix'] : $value;

        if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
            foreach ($_COOKIE as $key => $val) {

                if (0 === stripos($key, $prefix)) {

                    setcookie($_COOKIE[$key], '', time() - 3600, $config['path'], $config['domain']);

                    unset($_COOKIE[$key]);
                }
            }
        }

        return;
    }

    $name = $config['prefix'] . $name;

    if ('' === $value) {

        return isset($_COOKIE[$name]) ? unserialize($_COOKIE[$name]) : null; // 获取指定Cookie
    } else {

        if (is_null($value)) {

            setcookie($name, '', time() - 3600, $config['path'], $config['domain']);

            unset($_COOKIE[$name]); // 删除指定cookie
        } else {

            // 设置cookie

            $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;

            setcookie($name, serialize($value), $expire, $config['path'], $config['domain']);

            $_COOKIE[$name] = serialize($value);
        }
    }
}

//数组递归成XML元素

function array_to_xml($data, $attr=false) {

    if (is_object($data)) {

        $data = get_object_vars($data);
    }

    $xml = '';

    foreach ($data as $key => $val) {

        if ($attr) {

            is_numeric($key) && $key = "item id=\"$key\"";
        } else {

            is_numeric($key) && $key = "item";
        }

        $xml.="<$key>";

        $xml.= ( is_array($val) || is_object($val)) ? array_to_xml($val) : $val;

        list($key, ) = explode(' ', $key);

        $xml.="</$key>";
    }

    return $xml;
}

//MSN feed XML生成

function msnfeed($data, $root="root", $id=1) {

    $xml = '<?xml version="1.0" encoding="utf-8"?>';

    if (is_object($data) || is_array($data)) {

        $dataNum = count($data);
    }

    $xml.='<' . $root . ' version="2.0" id="' . $id . '">';

    $xml.= array_to_xml($data);

    $xml.='</' . $root . '>';

    return $xml;
}

//递归创建XML文件,如果文件路径存在并可用创建，否则返回字符串

function make_msnfeed_xml($data, $root='root', $path='', $id=1) {

    if (is_array($data) && count($data) > 0) {

        $xml = msnfeed($data, $root, $id);

        if (empty($path))
            return $xml;

        if (file_put_contents($path, $xml)) {

            return true;
        } else {

            return false;
        }
    } else {

        return false;
    }
}

//设置变量

function set_variable($name, $value='') {

    if (empty($name))
        throw_exception("Variable name can not be empty");

    if (is_array($value) && !empty($value)) {

        $val = json_encode($value);
    } else {

        if (is_string($value) || is_numeric($value)) {

            $val = json_encode($value);
        } else {

            $val = "";
        }
    }

    $dbVar = new csyr("variable");

    $nameArr = $dbVar->find($name);

    if (is_array($nameArr)) {

        if ($dbVar->setField("value", $val, "name='$name'")) {

            return true;
        } else {

            return false;
        }
    } else {

        if ($dbVar->add(array("name" => $name, "value" => "$val"))) {

            return true;
        } else {

            return false;
        }
    }

    return false;
}

//获取变量值

function get_variable($name, $index=null) {

    if (empty($name))
        throw_exception("Variable name can not be empty");

    $dbVar = new csyr("variable");

    $nameArr = $dbVar->find($name);

    if (is_array($nameArr) && !empty($nameArr['value'])) {

        $val = json_decode($nameArr['value'], true);

        if (is_null($index)) {

            return $val;
        } else {

            return $val[$index];
        }
    } else {

        if (!is_array($nameArr)) {

            return false;
        } else {

            return '';
        }
    }
}

//删除变量

function del_variable($name) {

    if (empty($name))
        throw_exception("Variable name can not be empty");

    $dbVar = new csyr("variable");

    if ($dbVar->delete($name)) {

        return true;
    } else {

        return false;
    }
}

//重定义IMG

function ResizeImage($src_file="", $dest_file="", $new_size=array('width' => 100, 'height' => 78), $quantity="100", $method="gd2") {

    //get infomation of iamge

    /*

      0 => width

      1 => height

      2 => 1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，15 = WBMP，16 = XBM

      3 => height="yyy" width="xxx"

     */

    $imginfo = getimagesize($src_file);

    if ($imginfo == null)
        return false;



    // GD can only handle JPG & PNG images

    if ($imginfo[2] != JPG && $imginfo[2] != PNG && $inginfo[2] != GIF && ($method == 'gd1' || $method == 'gd2')) {

        die("file is not be supported");

        return false;
    }

    $srcWidth = $imginfo[0];

    $srcHeight = $imginfo[1];



    $radio = max(($srcWidth / $new_size['width']), ($srcHeight / $new_size['height']));

    $destWidth = (int) $srcWidth / $radio;

    $destHeight = (int) $srcHeight / $radio;



    switch ($method) {

        case "gd1" :

            if (!function_exists('imagecreatefromjpeg')) {

                die("PHP running on your server does not support the GD image library");
            }

            if ($imginfo[2] == JPG)
                $src_img = imagecreatefromjpeg($src_file);

            elseif ($imginfo[2] == PNG)
                $src_img = imagecreatefrompng($src_file);

            else
                $src_img = imagecreatefromgif($src_file);

            if (!$src_img) {

                return false;
            }

            $dst_img = imagecreate($destWidth, $destHeight);

            imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int) $destHeight, $srcWidth, $srcHeight);

            imagejpeg($dst_img, $dest_file, $quantity);

            imagedestroy($src_img);

            imagedestroy($dst_img);

            break;



        case "gd2" :

            // check if support GD2

            if (!function_exists('imagecreatefromjpeg')) {

                die("PHP running on your server does not support the GD image library");
            }

            if (!function_exists('imagecreatetruecolor')) {

                die("PHP running on your server does not support GD version 2.x, please change to GD version 1.x on your method");
            }

            if ($imginfo[2] == JPG)
                $src_img = imagecreatefromjpeg($src_file);

            elseif ($imginfo[2] == PNG)
                $src_img = imagecreatefrompng($src_file);

            else
                $src_img = imagecreatefromgif($src_file);

            if (!$src_img) {

                return false;
            }

            $dst_img = imagecreatetruecolor($destWidth, $destHeight);

            imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int) $destHeight, $srcWidth, $srcHeight);

            imagejpeg($dst_img, $dest_file, $quantity);

            imagedestroy($src_img);

            imagedestroy($dst_img);

            break;
    }

    // Set mode of uploaded picture

    chmod($dest_file, 0755);



    // We check that the image is valid

    $imginfo = @getimagesize($dest_file);

    if ($imginfo == null) {

        @unlink($dest_file);

        return false;
    } else {

        return true;
    }
}

//数组去空值

function array_remove_empty(&$arr, $trim = true) {

    foreach ($arr as $key => $value) {

        if (is_array($value)) {

            if (empty($value))
                unset($arr[$key]);

            continue;

            $arr[$key] = array_diff($value, array('', null));

            array_remove_empty($arr[$key]);
        } else {

            if ($value == '') {

                unset($arr[$key]);
            } elseif ($trim) {

                $arr[$key] = $value;
            }
        }
    }
}

//数组去除值左右的空白符或空格

function array_trim(& $array, $all=false) {

    if (!is_array($array)

        )return false;

    foreach ($array as $k => $v) {

        if (is_array($v)) {

            array_trim($array[$k], $all);
        } else {

            if ($all)
                $array[$k] = str_replace(array('\n', '\r'), '', trim($v));

            else
                $array[$k] = trim($v);
        }
    }
}

/**

  +----------------------------------------------------------

 * 对多维数组排序

  +----------------------------------------------------------

 * @access public

  +----------------------------------------------------------

 * @param array $arr 要排序的数组

 * @param string/int $field 排列字段

 * @param string $sort_type 排列类型

  +----------------------------------------------------------

 * @return string

  +----------------------------------------------------------

 */
define('ASC_AZ', 1000);

define('DESC_AZ', 1001);

define('ASC_NUM', 1002);

define('DESC_NUM', 1003);

function stickysort($arr, $field, $sort_type, $sticky_fields = array()) {

    $i = 0;

    foreach ($arr as $value) {

        $is_contiguous = true;

        if (!empty($grouped_arr)) {

            $last_value = end($grouped_arr[$i]);



            if (!($sticky_fields == array())) {

                foreach ($sticky_fields as $sticky_field) {

                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {

                        $is_contiguous = false;

                        break;
                    }
                }
            }
        }

        if ($is_contiguous)
            $grouped_arr[$i][] = $value;

        else
            $grouped_arr[++$i][] = $value;
    }

    $code = '';

    switch ($sort_type) {

        case ASC_AZ:

            $code .= 'return strcasecmp($a["' . $field . '"], $b["' . $field . '"]);';

            break;

        case DESC_AZ:

            $code .= 'return (-1*strcasecmp($a["' . $field . '"], $b["' . $field . '"]));';

            break;

        case ASC_NUM:

            $code .= 'return ($a["' . $field . '"] - $b["' . $field . '"]);';

            break;

        case DESC_NUM:

            $code .= 'return ($b["' . $field . '"] - $a["' . $field . '"]);';

            break;
    }



    $compare = create_function('$a, $b', $code);



    foreach ($grouped_arr as $grouped_arr_key => $grouped_arr_value)
        usort($grouped_arr[$grouped_arr_key], $compare);



    $arr = array();

    foreach ($grouped_arr as $grouped_arr_key => $grouped_arr_value)
        foreach ($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key => $grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];



    return $arr;
}

/**

  +----------------------------------------------------------

 * 生成静态页面

  +----------------------------------------------------------

 * @access public

  +----------------------------------------------------------

 * @param string $baseUrl 要生成静态页面的动太页面

 * @param string $newFile 静态页面保存地址及文件名称

  +----------------------------------------------------------

 * @return int

  +----------------------------------------------------------

 */
function staticPage($baseUrl, $newFile='') {

    if (!$str = file_get_contents($baseUrl)) {

        return 0;
    }

    $oldFileName = str_replace('/', '', strrchr($baseUrl, '/'));

    if (strpos($oldFileName, '.') === false) {

        $fileName = $oldFileName . '.html';
    } else {

        $fileName = substr($oldFileName, 0, strrpos($oldFileName, '.')) . ".html";
    }

    return file_put_contents((empty($newFile) ? "./$oldFileName" : $newFile), $str);
}

//递规的对',",\ 运用反斜杠法则

function addslashes_deep($value) {

    if (empty($value)) {

        return $value;
    } else {

        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}

//运行时间

function G($start, $end='', $dec=3) {

    static $_info = array();

    if (!empty($end)) { // 统计时间
        if (!isset($_info[$end])) {

            $_info[$end] = microtime(TRUE);
        }

        return number_format(($_info[$end] - $_info[$start]), $dec);
    } else { // 记录时间
        $_info[$start] = microtime(TRUE);
    }
}

//转换路径中的斜线规则

function changeSlashes($path='') {

    return str_replace(array("\\", "\\\\", "//"), '/', $path);
}

//增加路径尾部斜线

function addSlashToEnd($str) {

    if (empty($str))
        return '/';

    $str = changeSlashes($str);

    if (substr($str, -1) != '/') {

        return $str . '/';
    } else {

        return $str;
    }
}

//删除路径尾部斜线

function removeEndSlash($str) {

    if (empty($str))
        return '/';

    $str = changeSlashes($str);

    return trim($str, '/');
}

//检测数组

function isArray($array) {

    return is_array($array) ? $array : array();
}

//检测是否为数组的结尾

function isEnd($array, $item='') {

    if (!is_array($array)

        )return false;

    $endVal = array_pop($array);

    if (is_null($endVal)

        )return false;

    if ($endVal === $item) {

        return true;
    } else {

        return false;
    }
}


/**
 * 获取请示路径
 * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
 * generate an equivalent using other environment variables.
 */
function request_uri() {

    if (isset($_SERVER['REQUEST_URI'])) {
        $uri = $_SERVER['REQUEST_URI'];
    } else {
        if (isset($_SERVER['argv'])) {
            $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
        } elseif (isset($_SERVER['QUERY_STRING'])) {
            $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
        } else {
            $uri = $_SERVER['SCRIPT_NAME'];
        }
    }
    // Prevent multiple slashes to avoid cross site requests via the FAPI.
    $uri = '/' . ltrim($uri, '/');

    return $uri;
}

//环境是否能rewrite
// return bool
function env_can_rewrite() {
    return in_array('mod_rewrite', apache_get_modules());
}